<?php session_start();
$host = $_SERVER['HTTP_HOST'];
if ($_SERVER['SERVER_NAME'] == 'localhost'){$uri="/kalender";}else{$uri="";}
if (!isset($_SESSION['id_user']) || $_SESSION['id_user']=='') {
	echo "<script language=Javascript> location.href='http://$host$uri/index.php'; </script>";	
}else{
		
	if (!is_object($bd)){	
		//me conecto a la base de datos
		require("../globals/Db.class.php");
		require("../globals/Conf.class.php");
		$bd=Db::getInstance();	
	}	
	if (!is_object($util)){	
		include("../globals/Util.class.php");
		$util=Util::getInstance();
	}
	

	if (!($util->administrarTiempoSesion())){
		echo "<script language=Javascript> location.href='http://$host$uri/timeout.php'; </script>";
	}else if (!($util->administrarAcceso("facturacion"))){
		echo "<script language=Javascript> location.href='http://$host$uri/sinAcceso.php'; </script>";
	}
				
	$idOT = $bd->san($_POST["idOT"]);
	$numFact = $bd->san($_POST["numFact"]);
	$cantItems = $util->getItemsQuantityFormOT($bd, $idOT);
	if ($cantItems == 0){
		echo "msg:nok##EMPTY_OT";
	}else{
		if (is_numeric($numFact)){
			try {
				$bd->beginTransaction();
			
					$query = "insert into facturas (numero, id_ot, fecha_creacion) values ('$numFact', $idOT, now());";
					$result = $bd->eje($query);	
					$idFactura = $bd->lastID();			
						
					$query = "update ordenes_trabajo set id_factura = $idFactura, estado =  'C' where id = $idOT;";
					$result = $bd->eje($query);
					
					$id_user = $_SESSION['id_user'];
					$nombre = $bd->san($_POST["rs"]);
					$query = "INSERT INTO logs (usuario_id, accion, fecha) values ($id_user, 'Se ha creado la factura: $numFact (OT:$idOT)', now());";
					$bd->eje($query);	
				
				$bd->commit();
				echo "msg:ok##$idFactura";	
			} catch (Exception $e) {	   
			    $bd->rollback();
			    echo "msg:nok";
			}
		}else{
			echo "msg:nok##NOT_NUMERIC";
		}	
	}
}
?>